package com.np.adapterdemo2;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.np.adapterdemo2.pojo.Blog;

import java.util.ArrayList;
import java.util.List;

public class BaseAdapterActivity extends AppCompatActivity {

    private static final String TAG = BaseAdapterActivity.class.getSimpleName();
    private List<Blog> mBlogList = new ArrayList<>();
    private BlogAdapter mAdapter;
    private ListView mLvBlog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_adapter);

        mLvBlog =  findViewById(R.id.lv_blog);

        // 模拟数据
        for (int i = 0; i < 50; i++) {
            Blog blog = new Blog();
            blog.setTitle("标题" + i);
            blog.setContent("内容" + i);
            mBlogList.add(blog);
        }

        mAdapter = new BlogAdapter(this);
        mLvBlog.setAdapter(mAdapter);
    }

    public final class BlogViewHolder {
        public TextView tvTitle;
        public Button buttonSelect;
    }

    public class BlogAdapter extends BaseAdapter {

        private LayoutInflater mLayoutInflater;

        public BlogAdapter(Context context) {
            this.mLayoutInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return mBlogList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            BlogViewHolder holder = null;

            if (convertView == null) {
                convertView = mLayoutInflater.inflate(R.layout.item_blog, parent, false);

                holder = new BlogViewHolder();
                convertView = mLayoutInflater.inflate(R.layout.item_blog, null);
                holder.tvTitle = convertView.findViewById(R.id.tv_title);
                holder.buttonSelect = convertView.findViewById(R.id.button_select);
                convertView.setTag(holder);
            } else {
                holder = (BlogViewHolder) convertView.getTag();
            }

            Blog blog = mBlogList.get(position);

            holder.tvTitle.setText(blog.getTitle());
            holder.buttonSelect.setOnClickListener(v -> {
                getIntent().putExtra("entity", blog);
                setResult(Activity.RESULT_OK, getIntent());
                finish();
            });

            return convertView;
        }
    }
}